import React, { useState, useEffect } from 'react';
import { Card, Form, Row, Col, Input, Select, Button, Table, Popconfirm, message, Badge, Divider, DatePicker } from 'antd';
import BreadcrumbBox from '@/components/Base/BreadcrumbBox';
import { withRouter } from 'react-router-dom';
import { formatBalance } from '@/utils/utils';
import { useDebounceFn, useSyncCallback, deepclone } from '@/utils';
import { Storage } from '@/assets/js/storage';
import { TOKEN } from '@/utils/constant'
import moment from 'moment';
import './index.scss';
import { 
  memberSum,
  memberPage,
  memberInfoSum,
  memberInfoPage,
} from '@/api/report'

let first = false
let orCToken = {}
const TradeReport = (props) => {
  const [searchForm] = Form.useForm();
  const { RangePicker } = DatePicker;
  // 筛选数据
  const [values] = useState({
    "time": [moment(),moment()],
  })
  // 详情 列表
  const [isDetail, setIsDetail] = useState(false)
  const [countDate, setCountDate] = useState('')
  const [initParams, setInitParams] = useState({
    currentPage: 1,
    pageSize: 20,
    time: [moment(),moment()],
  })
  // 分页
  const [total, setTotal] = useState(0)
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(20)
  const [dataSource, setDataSource] = useState([]);
  // 面包屑
  const breadcrumbList = ['报表管理', '会员买卖报表']
  // 布局
  const layout1 = { sm: 24, md: 12, lg: 12, xl: 6, xxl: 6 };
  const labelCol = { sm: 24, md: 8, lg: 8, xl: 8 };
  const wrapperCol = { sm: 24, md: 16, lg: 16, xl: 16 };
  const layoutbtn = { sm: 24, md: 24, lg: 24, xl: 12, xxl: 12 };
  
  const [formData, setFormData] = useState(values)
  let [loading, setLoading] = useState(false)
  // 表单头部
  const columns = [
    {
      title: '日期',
      dataIndex: 'countDate',
      key: 'countDate',
      align: 'center',
    },
    {
      title: '买入人数',
      dataIndex: 'buyPeoples',
      key: 'buyPeoples',
      align: 'center',
      render: (text: any) => text||text===0 ? text : '--',
    },
    {
      title: '买入笔数',
      dataIndex: 'buyCounts',
      key: 'buyCounts',
      align: 'center',
      render: (text: any) => text||text===0 ? text : '--',
    },
    {
      title: '买入金额',
      dataIndex: 'buyAmount',
      key: 'buyAmount',
      align: 'center',
      render: (text: any, record: any, index: any) => {
        if((index === dataSource.length-1) || (index === dataSource.length-2)){
          return text;
        }else{
          return <a onClick={()=>{goDetail(record)}}>{text}</a>
        }
      }
    },
    {
      title: '买入手续费',
      key: 'buyFee',
      dataIndex: 'buyFee',
      align: 'center',
      render: (text: any) => text||text===0 ? text : '--',
    },
    {
      title: '卖出人数',
      key: 'sellPeoples',
      dataIndex: 'sellPeoples',
      align: 'center',
      render: (text: any) => text||text===0 ? text : '--',
    },
    {
      title: '卖出笔数',
      key: 'sellCounts',
      dataIndex: 'sellCounts',
      align: 'center',
      render: (text: any) => text||text===0 ? text : '--',
    },
    {
      title: '卖出金额',
      key: 'sellAmount',
      dataIndex: 'sellAmount',
      align: 'center',
      render: (text: any) => text||text===0 ? text : '--',
    },
    {
      title: '卖出手续费',
      key: 'sellFee',
      dataIndex: 'sellFee',
      align: 'center',
      render: (text: any) => text||text===0 ? text : '--',
    },
  ];
  const columnsDetail = [
    {
      title: '日期',
      dataIndex: 'countDate',
      key: 'countDate',
      align: 'center',
    },
    {
      title: '账号',
      dataIndex: 'username',
      key: 'username',
      align: 'center',
    },
    {
      title: '真实姓名',
      key: 'realName',
      dataIndex: 'realName',
      align: 'center',
    },
    {
      title: '买入笔数',
      key: 'buyCounts',
      dataIndex: 'buyCounts',
      align: 'center',
      render: (text: any) => text||text===0 ? text : '--',
    },
    {
      title: '买入金额',
      key: 'buyAmount',
      dataIndex: 'buyAmount',
      align: 'center',
      render: (text: any) => text||text===0 ? text : '--',
    },
    {
      title: '买入手续费',
      key: 'buyFee',
      dataIndex: 'buyFee',
      align: 'center',
      render: (text: any) => text||text===0 ? text : '--',
    },
    {
      title: '卖出笔数',
      key: 'sellCount',
      dataIndex: 'sellCount',
      align: 'center',
      render: (text: any) => text||text===0 ? text : '--',
    },
    {
      title: '卖出金额',
      key: 'sellAmount',
      dataIndex: 'sellAmount',
      align: 'center',
      render: (text: any) => text||text===0 ? text : '--',
    },
    {
      title: '卖出手续费',
      key: 'sellFee',
      dataIndex: 'sellFee',
      align: 'center',
      render: (text: any) => text||text===0 ? text : '--',
    },
  ];
  const addAct = (aValue=0,bValue=0) => {
    let sum = 0;
    aValue = aValue.toString()
    bValue = bValue.toString()
    let aLength = aValue.indexOf('.') !== -1 ? aValue.split('.')[1].length : 0;
    let bLength = bValue.indexOf('.') !== -1 ? bValue.split('.')[1].length : 0;
    if(aLength > bLength){
      sum = (parseFloat(aValue) + parseFloat(bValue)).toFixed(aLength)
      console.log(aLength)
    }else{
      sum = (parseFloat(aValue) + parseFloat(bValue)).toFixed(bLength)
    }
    return sum;
  };
  // 提交弹框表单做防抖处理
  const onFinish = async () => {
    let values = deepclone(formData)
    try {
      let params = {
         startDate: moment(values.time[0]).format('YYYY-MM-DD'),
         endDate: moment(values.time[1]).format('YYYY-MM-DD'),
         currentPage,
         pageSize,
       }
      if(isDetail===true){
        if(values.merchantNo){
          params.merchantNo = values.merchantNo;
        }
        params.countDate = countDate;
      }else{
        setInitParams({
          currentPage,
          pageSize,
          time: [moment(values.time[0]).format('YYYY-MM-DD'),moment(values.time[1]).format('YYYY-MM-DD')]
        })
      } 
      setLoading(true)
      let res = isDetail===true ? await memberInfoPage(params, orCToken) : await memberPage(params, orCToken)
      if(res.code === 0) {
        if(res.data&&res.data.records){
          let memberListTotal = {
            countDate: '',
            drawAmount: 0,
            drawFee: 0,
            rechargeAmount: 0,
            rechargeFee: 0,
            totalFee: 0
          };
          for (let i = 0; i < res.data.records.length; i++) {
            memberListTotal.countDate = '总计:' + res.data.records.length + '行';
            
            memberListTotal.buyAmount = addAct(memberListTotal.buyAmount,res.data.records[i].buyAmount);
            memberListTotal.buyCounts = addAct(memberListTotal.buyCounts,res.data.records[i].buyCounts);
            memberListTotal.buyFee = addAct(memberListTotal.buyFee,res.data.records[i].buyFee);
            memberListTotal.buyPeoples = addAct(memberListTotal.buyPeoples,res.data.records[i].buyPeoples);
            
            memberListTotal.sellAmount = addAct(memberListTotal.sellAmount,res.data.records[i].sellAmount);
            memberListTotal.sellCounts = addAct(memberListTotal.sellCounts,res.data.records[i].sellCounts);
            memberListTotal.sellFee = addAct(memberListTotal.sellFee,res.data.records[i].sellFee);
            memberListTotal.sellPeoples = addAct(memberListTotal.sellPeoples,res.data.records[i].sellPeoples);
          }
          setDataSource([...res.data.records, memberListTotal])
          setTotal(res.data.total)
          getTotalFn()
        }else{
          setDataSource([])
        }
      }else{
        setDataSource([])
      }
      setLoading(false)
    } catch (error) {
      console.log(error)
    }
  };
  // 等state改变后再执行
  const getTotalFn = useSyncCallback(() => {
    getTotal()
  })
  const getTotal = async () => {
   let values = deepclone(formData)
   try {
       let params = {
         startDate: moment(values.time[0]).format('YYYY-MM-DD'),
         endDate: moment(values.time[1]).format('YYYY-MM-DD'),
         currentPage,
         pageSize,
       }
      if(isDetail===true){
        if(values.merchantNo){
          params.merchantNo = values.merchantNo;
        }
        params.countDate = countDate;
      }
      let res = isDetail === true ? await memberInfoSum(params, orCToken) : await memberSum(params, orCToken)
      if(res.code === 0) {
        let sumObj = {
          ...res.data,
          countDate: '跨页统计',
        }
        setDataSource([
          ...dataSource,
          sumObj,
        ])
      }
    } catch (error) {
      console.log(error)
    }
  };
  const goDetail = (data) => {
    setTotal(0)
    setDataSource([])
    setCurrentPage(1)
    setPageSize(20)
    setIsDetail(true)
    setCountDate(data.countDate)
    searchData()
  }
  const back = () => {
    setTotal(0)
    setDataSource([])
    setCurrentPage(initParams.currentPage)
    setPageSize(initParams.pageSize)
    setIsDetail(false)
    setCountDate('')
    setFormData({
      ...formData,
      time: [moment(initParams.time[0]),moment(initParams.time[1])]
    })
    searchForm.setFieldsValue({
      "time": [moment(initParams.time[0]),moment(initParams.time[1])]
    });
    searchData()
  }
  
  // 等state改变后再执行
  const searchData = useSyncCallback(() => {
    onFinish()
  })
  //改变搜索条件更新
  useEffect(() => {
    if(first) {
      searchData()
    }
    return () => {};
  // eslint-disable-next-line react-hooks/exhaustive-deps
  } , [currentPage, pageSize])
  // 首次更新
  useEffect(() => {
    searchData()
    first = true
    return () => { 
      first = false
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  } , [])
  
  // 初始化
  return (
  <div>
    <div>
      <BreadcrumbBox list={breadcrumbList}></BreadcrumbBox>
      <div className='agent-main'>
        <Form
          initialValues={values} 
          form={searchForm} 
          onFinish={(val) => {
            setFormData(val)
            searchData()
          }}>
          <Card className="formCard" style={{ width: '100%' }} bordered={false}>
            <Row>
              <Col {...layout1}>
                <Form.Item
                  name="time"
                  className="formItem"
                  label="日期范围"
                  labelCol={labelCol}
                  wrapperCol={wrapperCol}
                >
                  <RangePicker allowClear={false} />
                </Form.Item>
              </Col>
              {
                isDetail === true
                ?
                <>
                  <Col {...layout1}>
                    <Form.Item
                      name="merchantNo"
                      className="formItem"
                      label="商户编号"
                      labelCol={labelCol}
                      wrapperCol={wrapperCol}
                    >
                      <Input />
                    </Form.Item>
                  </Col>
                </>
                :
                ''
              }
              <Col {...layout1}>
                <span className="buttonLeft">
                  <Button type="primary" htmlType="submit">
                    查询
                  </Button>
                  <Button
                    className="reset-btn"
                    type="default"
                    onClick={() => {
                      searchForm.resetFields()
                    }}
                  >
                    重置
                  </Button>
                </span>
              </Col>
              {
                isDetail === true
                ?
                <Col {...layoutbtn}>
                  <Button
                    style={{'float': 'right'}}
                    type="default" 
                    onClick={() => {back()}}>
                    返回
                  </Button>
                </Col>
                :
                ''
              }
              
            </Row>
          </Card>
        </Form>
        <div className='table-box'>
          <Card>
            <div className='table'>
              <Table
                loading={loading}
                size='middle'
                bordered
                scroll={{ x: 1224 }}
                rowKey={'id'}
                className='antd-table'
                dataSource={dataSource}
                pagination={{
                  size: 'default',
                  current: currentPage,
                  total: total,
                  showSizeChanger: true,
                  pageSize: pageSize,
                  onChange: (page, pagesize) => {}
                }}
                columns={isDetail===true?columnsDetail:columns} />
            </div>
          </Card>
        </div>
      </div>
    </div>
  </div>
  )
}
export default withRouter(TradeReport)